import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { EditIcon, PlusIcon, UsersRoundIcon } from "lucide-react";
import * as React from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import z from "zod";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { authClient } from "@/lib/auth-client";

const schema = z.object({
  name: z.string().min(1, "Name is required"),
  slug: z.string().min(1, "Slug is required"),
});

type FormData = z.infer<typeof schema>;

type Mode = "create" | "edit";

interface Props {
  mode: Mode;
  organization?: {
    id: string;
    name: string;
    slug: string;
  };
}

export function OrganizationFormDialog({ mode, organization }: Props) {
  const queryClient = useQueryClient();
  const [open, setOpen] = React.useState(false);

  const isEdit = mode === "edit";

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<FormData>({
    resolver: zodResolver(schema),
    defaultValues: isEdit
      ? { name: organization?.name, slug: organization?.slug }
      : { name: "", slug: "" },
  });

  const mutation = useMutation({
    mutationFn: async (data: FormData) => {
      if (isEdit && organization) {
        const { error } = await authClient.organization.update({
          organizationId: organization.id,
          data,
        });
        if (error) throw error;
        toast.success("Organization updated successfully!");
      } else {
        const { error } = await authClient.organization.create({
          ...data,
          keepCurrentActiveOrganization: true,
        });
        if (error) throw error;
        toast.success("Organization created successfully!");
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["organizations"] });
      setOpen(false);
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  React.useEffect(() => {
    if (open) {
      reset(
        isEdit ? { name: organization?.name, slug: organization?.slug } : { name: "", slug: "" },
      );
    }
  }, [open, isEdit, organization, reset]);

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        {isEdit ? (
          <Button variant="ghost" size="icon">
            <EditIcon />
          </Button>
        ) : (
          <Button size="sm">
            <PlusIcon />
            Add Organization
          </Button>
        )}
      </DialogTrigger>

      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>{isEdit ? "Edit organization" : "Create a new organization"}</DialogTitle>
          <DialogDescription>
            {isEdit
              ? "Update the name and slug of your organization."
              : "You can use the name of your company or department."}
          </DialogDescription>
        </DialogHeader>

        <form
          onSubmit={handleSubmit((data) => mutation.mutate(data))}
          className="flex flex-col gap-4"
        >
          <div className="grid gap-2">
            <Label htmlFor="name">Name</Label>
            <Input id="name" {...register("name")} />
            {errors.name && <p className="text-destructive text-xs">{errors.name.message}</p>}
          </div>

          <div className="grid gap-2">
            <Label htmlFor="slug">Slug</Label>
            <Input id="slug" {...register("slug")} />
            {errors.slug && <p className="text-destructive text-xs">{errors.slug.message}</p>}
          </div>

          <DialogFooter className="flex items-center justify-between">
            <DialogClose asChild>
              <Button variant="outline" type="button">
                Cancel
              </Button>
            </DialogClose>
            <Button type="submit" disabled={mutation.isPending}>
              {mutation.isPending ? "Saving..." : "Save"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
